package org.xin.generate.service.impl;

import cn.hutool.core.exceptions.StatefulException;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.xin.framework.base.service.impl.IBaseServiceImpl;
import org.xin.generate.pojo.config.Source;
import org.xin.generate.pojo.entity.Generate;
import org.xin.generate.mapper.GenerateMapper;
import org.xin.generate.service.GenerateService;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：xin
 * @date ：Created in 19:24
 * @description：
 * @modified By：$
 * @version: $
 */
@Slf4j
@Service
public class GenerateServiceImpl extends IBaseServiceImpl<Generate, GenerateMapper> implements GenerateService {

    @Override
    public List<String> getSchemas() {
        return baseMapper.getSchemas(source.getDatabase());
    }


    @Override
    public boolean generator(AutoGenerator generator) {
        try {
            log.warn("G-代码生产开始");
            generator.execute();
            log.warn("G-代码生产结束");
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Resource
    private Source source;



    @Override
    public DataSourceConfig getDataSourceConfig() {
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setUrl(source.getUrl())
                .setDriverName(source.getDriverClassName())
                .setUsername(source.getUsername())
                .setPassword(source.getPassword());
        return dataSourceConfig;
    }

    @Override
    public AutoGenerator init(Generate generate) {
        try {
            DataSourceConfig dataSourceConfig = this.getDataSourceConfig();
            PackageConfig packageConfig = this.getPackageConfig(generate);
            StrategyConfig strategyConfig = this.getStrategyConfig(generate);
            TemplateConfig templateConfig = this.getTemplateConfig(generate.getTemplatePath());
            GlobalConfig globalConfig = this.getGlobalConfig(generate);

            AutoGenerator generator = this.initConfig(
                    packageConfig, dataSourceConfig, strategyConfig, templateConfig, globalConfig
            );
            List<FileOutConfig> focList = this.getFileOutConfig();
            Map<String, Object> map = new HashMap<>();
            map.put("ID", "Long");
            InjectionConfig injectionConfig = this.getInjectionConfig(map);
            injectionConfig.setFileOutConfigList(focList);
            generator.setCfg(injectionConfig);
            generator.setTemplateEngine(new FreemarkerTemplateEngine());
            return generator;
        } catch (Exception e) {
            throw new StatefulException("生成器加载失败");
        }

    }


    @Override
    public PackageConfig getPackageConfig(Generate generate) {
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setModuleName(generate.getModuleName()).setParent("org.xin.framework");
        return packageConfig;
    }

    @Override
    public StrategyConfig getStrategyConfig(Generate generate) {
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);
        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
        if (StrUtil.isNotEmpty(generate.getSuperEntityClass())) {
            // 公共父类
            strategyConfig.setSuperEntityClass(generate.getSuperEntityClass());
        }
        if (StrUtil.isNotEmpty(generate.getSuperControllerClass())) {
            // 公共父类
            strategyConfig.setSuperControllerClass(generate.getSuperControllerClass());
        }

        strategyConfig.setEntityLombokModel(true);
        strategyConfig.setRestControllerStyle(true);

        // 写于父类中的公共字段
//        strategyConfig.setSuperEntityColumns("id");
        strategyConfig.setInclude(generate.getTableNames().split(","));
        strategyConfig.setControllerMappingHyphenStyle(true);
//        strategyConfig.setTablePrefix(strategy.getModuleName() + "_");
        return strategyConfig;
    }

    @Override
    public TemplateConfig getTemplateConfig(String templatePath) {
        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        if (StrUtil.isNullOrUndefined(templatePath)) {
            return templateConfig;
        }

        // 配置自定义输出模板
        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        templateConfig.setEntity("templates/[path]/entity.java".replace("[path]", templatePath));
        templateConfig.setController("templates/[path]/controller.java".replace("[path]", templatePath));
        templateConfig.setService("templates/[path]/service.java".replace("[path]", templatePath));
        templateConfig.setServiceImpl("templates/[path]/serviceImpl.java".replace("[path]", templatePath));
        templateConfig.setMapper("templates/[path]/mapper.java".replace("[path]", templatePath));
        templateConfig.setXml("templates/[path]/mapper.xml".replace("[path]", templatePath));
        return templateConfig;
    }

    @Override
    public GlobalConfig getGlobalConfig(Generate generate) {
        GlobalConfig globalConfig = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
//        File file = new File(projectPath);
        globalConfig.setOutputDir(/*file.getParent()*/ projectPath + "\\xin-app-model" + "\\src\\main\\java\\");
        globalConfig.setAuthor(generate.getAuthor());
        globalConfig.setOpen(false);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        return globalConfig;
    }

    @Override
    public InjectionConfig getInjectionConfig(Map<String, Object> map) {
        InjectionConfig injectionConfig = new InjectionConfig() {
            @Override
            public void initMap() {
                this.setMap(map);
            }
        };
        return injectionConfig;
    }

    @Override
    public List<FileOutConfig> getFileOutConfig() {
        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
//        // 自定义配置会被优先输出
//        focList.add(new FileOutConfig(templatePath) {
//            @Override
//            public String outputFile(TableInfo tableInfo) {
//                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
//                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
//                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
//            }
//        });
        return focList;
    }


    @Override
    public AutoGenerator initConfig(PackageConfig packageConfig, DataSourceConfig dataSourceConfig, StrategyConfig strategyConfig, TemplateConfig template, GlobalConfig globalConfig) {
        AutoGenerator generator = new AutoGenerator();
        //TODO 加入模板
//        generator.setTemplateEngine(new FreemarkerTemplateEngine());
        return generator.setConfig(new ConfigBuilder(packageConfig, dataSourceConfig, strategyConfig, template, globalConfig));
    }

    /*@Override
    public AutoGenerator initConfig(AutoGenerator generator, List<FileOutConfig> focList, InjectionConfig injectionConfig) {
        injectionConfig.setFileOutConfigList(focList);
        return generator.setCfg(injectionConfig);
    }*/


    private void close(Connection con) {
        try {
            con.close();
            log.warn("数据库链接已关闭。");
        } catch (SQLException throwables) {
            log.error("数据库链接关闭异常");
        }
    }
}
